package thread_base.thread_safe;

import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;

public class CountingFactorizer {
    private final AtomicLong count = new AtomicLong(0);
    public void service(ServletRequest req, ServletResponse resp) {
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = factor(i);
        // 原子变量类操作
        count.incrementAndGet();
        encodeIntoResponse(resp, factors);
    }

    BigInteger[] factor(BigInteger i) {
        // Doesn't really factor
        return new BigInteger[]{i};
    }

    BigInteger extractFromRequest(ServletRequest req) {
        return new BigInteger("7");
    }

    void encodeIntoResponse(ServletResponse resp, BigInteger[] factors) {
    }

    public long getCount() {
        return count.get();
    }

    public static void main(String[] args) throws InterruptedException {
        CountingFactorizer countingFactorizer = new CountingFactorizer();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                countingFactorizer.service(null, null);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                countingFactorizer.service(null, null);
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("count: " + countingFactorizer.getCount());
    }
}
